﻿<template>
    <div class="app-container">
        <!-- 搜索区-->
        <el-form :model="queryParams" ref="queryForm"  :inline="true">
            <el-form-item label="用户名称" class="item">
                <el-input
                        v-model="queryParams.username"
                        placeholder="请输入用户名"
                        clearable
                        size="small"
                        style="width: 240px"
                        @keyup.enter.native="load"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="load">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="reset" >重置</el-button>
            </el-form-item>
        </el-form>

        <!--按钮区域    -->
        <el-row :gutter="10" class="mb8"   style="margin:5px">
            <el-button type="primary" plain  icon="el-icon-plus"  size="mini" @click="add()">新增</el-button>
            <el-button type="success" plain icon="el-icon-edit" size="mini"   >修改</el-button>
        </el-row>

        <!-- 列表区-->
        <el-table :data="tableData" :header-cell-style="{background:'#F8F8F9'}"  style="width: 100%">
            <el-table-column type="index"  :index="indexMethod" label="编号" width="100px"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="nickName" label="昵称"></el-table-column>
            <el-table-column prop="sex" label="性别" :formatter="formatSex"></el-table-column>
            <el-table-column prop="age" sortable label="年龄"></el-table-column>
            <el-table-column prop="roleName" label="角色"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column fixed="right" label="操作" width="260">
                <template #default="scope">
                    <button type="button" @click="handleEdit(scope.row)"  class="el-button el-button--text el-button--mini"><!----><i class="el-icon-edit"></i><span>修改</span></button>
                    <button type="button"  @click="handleDelete(scope.row)" class="el-button el-button--text el-button--mini"><!----><i class="el-icon-delete"></i><span style="color:red">删除</span></button>
                    <button type="button"   @click="resetPassword(scope.row)" class="el-button el-button--text el-button--mini"><!----><i class="el-icon-key"></i><span>重置密码</span></button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表分页-->
        <div style="margin: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"> //双引号里面的total是定义一个变量，在这里定义了，就需要在下面data里面初始化一下
            </el-pagination>

            <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :append-to-body="true" >
                <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="120px">
                    <el-form-item label="姓名:" prop="username">
                        <el-input v-model="editForm.username" style="width:80%"></el-input>
                    </el-form-item>

                    <el-form-item label="昵称:" prop="nickName">
                        <el-input v-model="editForm.nickName" style="width:80%"></el-input>
                    </el-form-item>

                    <el-form-item label="年龄:" prop="age">
                        <el-input v-model="editForm.age" style="width:80%"></el-input>
                    </el-form-item>

                    <el-form-item    label="性别:" prop="sex">
                        <el-radio-group v-model="editForm.sex" >
                            <el-radio   label="1" >男</el-radio>
                            <el-radio   label="2" >女</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="角色:" prop="roleId">
                        <el-radio-group v-model="editForm.roleId"  >
                            <el-radio v-for="(item,index) in roles" :key="index"  :label="item.roleId">{{item.roleName}}</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="地址:" prop="address">
                        <el-input type="textarea" v-model="editForm.address" style="width:80%"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="submitForm('editForm')">确 定</el-button>
                  </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import request from "../utils/request";
    import {mapState} from "vuex";

    export default {
        name: 'user',
        data() {
            return {
                title: '',
                radio:'1',
                dialogVisible: false,
                // 查询参数
                queryParams: {
                    username: '',
                },
                currentPage: 1,
                pageSize: 5,
                total: 0,  //默认10条
                tableData: [],
                editForm: {},
                roles: [], // 角色选项

                editFormRules: {
                    username: [
                        {required: true, message: '请输入用户名称', trigger: 'blur'}
                    ],
                    age: [
                        {required: true, message: '请输入年龄', trigger: 'blur'}
                    ],
                },

            }
        },

        //页面加载完立即执行的方法
        created() {
            this.load()
        },

        methods: {

            indexMethod(index) {
                return index+1 ;
            },


            //查询方法
            load() {
                request.get("/user/selectList", {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        username: this.queryParams.username
                    }
                }).then(res => {
                    this.tableData = res.data.list
                    this.total = res.data.total
                }).catch(error=>error)

            },

            //新增打开弹窗方法
            add() {
                this.dialogVisible = true;
                this.title = "新增"
                this.editForm = {sex:"1",roleId:3}; //清空表单中的值
                request.get("/user/info").then(res => {
                    this.roles=res.data.roles;
                }).catch(err =>err);

            },

            //保存
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        request.post('/user/' + (this.editForm.id?'update' : 'save'), this.editForm)
                            .then(res => {
                                if(res.code=='0'){
                                    this.$message({
                                        showClose: true,
                                        message: '恭喜你，操作成功',
                                        type: 'success',
                                        onClose:() => {
                                            this.getUserList()
                                        }
                                    });
                                    this.load();  //更新完成后，重新刷新表格数据
                                    this.dialogVisible = false
                                }

                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            //编辑打开弹窗方法
            handleEdit(row) {
                this.editForm = JSON.parse(JSON.stringify(row));  //将编辑的弹窗附上值

                request.get("/user/info").then(res => {
                    this.roles=res.data.roles;
                }).catch(err =>err);
                this.dialogVisible = true;  //打开编辑的弹窗（和新增用的一个弹窗）
                this.title = "编辑"
            },


            //删除方法
            handleDelete(row) {
                this.$confirm('确定要删除该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.delete("/user/del/" + row.id).then(res => {
                        if (res.code === '0') {
                            debugger
                            this.$message({
                                type: "success",
                                message: "删除成功"
                            })
                        }
                        this.load()
                    })
                })
            },


            //重置密码
            resetPassword(row){
                this.$confirm('确定要重置密码吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.get("/user/resetPassword/" + row.id).then(res => {
                        if (res.code === '0') {
                            this.$message({
                                type: "success",
                                message: res.msg
                            })
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg
                            })
                        }
                        this.load()
                    })
                })
            },


            /** 重置按钮操作 */
            reset() {
                this.queryParams = {};
            },

            /** 格式化男女 */
            formatSex(row,colum){
                return row.sex == '1' ? "男" : "女";
            },

            //在上面的data中，pageSize和currentPaage都有默认值，这里要触发分页，需要重新根据变量赋值
            //改变当前每页条数触发
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },

            //改变当前页码触发
            handleCurrentChange(pageNum) {
                this.currentPage = pageNum
                this.load()
            },

        }
    }
</script>

<style scoped>



</style>
